package edu.nepu.flink.api.state;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

/**
 * @Date 2024/3/2 10:42
 * @Created by chenshuaijun
 */
public class MapStateDemo {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> source = env.socketTextStream("hadoop102", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                        try {
                            String[] split = value.split(",");
                            if (split.length == 3) {
                                out.collect(new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2])));
                            }
                        } catch (Exception e){
                            // 如果因为数据输入错误，产生的异常直接忽略掉
                        }
                    }
                }).assignTimestampsAndWatermarks(WatermarkStrategy.<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
            @Override
            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                return element.getTs() * 1000;
            }
        }));
        /**
         * TODO 使用MapState要做的需求
         *          针对每种传感器输出不同水位值出现的次数
         */
        source.keyBy(WaterSensor::getId).process(new KeyedProcessFunction<String, WaterSensor, String>() {
            MapState<Integer,Integer> mapState;

            @Override
            public void open(Configuration parameters) throws Exception {
                // 状态的初始化必须要再在Open方法中进行，否者会报错误
                mapState = getRuntimeContext().getMapState(new MapStateDescriptor<>("map-state",Types.INT,Types.INT));
            }

            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                int vc = value.vc;
                if (mapState.contains(vc)){
                    mapState.put(vc,mapState.get(vc)+1);
                } else {
                    mapState.put(vc,1);
                }
                StringBuffer buffer = new StringBuffer();
                buffer.append("************key="+ctx.getCurrentKey()+"*************\n");
                for (Map.Entry<Integer, Integer> entry : mapState.entries()) {
                    buffer.append(entry).append("\n");
                }
                out.collect(buffer.toString());
            }
        }).print();

        env.execute();
    }
}
